import * as api from '@/api'
import Vue from 'vue'
import Vuex from 'vuex'
import createLogger from 'vuex/dist/logger'
import user from './modules/user'
import token from './modules/token'
import types from './types'


Vue.use(Vuex)

const debug = process.env.NODE_ENV !== 'production'


const state = {
  forcedLogin: false,
  hasLogin: localStorage.getItem(types.USER_NAME) ? true : false,
}

const mutations = {
  login(state) {
    state.hasLogin = true;
  },
  
  logout(state) {
    state.hasLogin = false;
    state.token.value = '';
    state.user.username = '';
  },
  
}

const actions = {
  
  //根据用户名和密码登录，并设置相应的状态信息
  async login(context, userInfo) {
    
    if(!(userInfo.hasOwnProperty('username') && userInfo.hasOwnProperty('password'))) {
      return false;
    }
    
    const res = await api.token.create(userInfo)
    if(res.errno === 0 && res.data.token) {
      context.commit('user/setUserName', res.data.username);
      context.commit('token/setToken', res.data.token);
      context.commit('login'); //修改登录状态
      return true;
    } else {
      return false;
    }
  },
  
  //注册并自动登录
  async register(context, userInfo) {
    const res = await api.user.create(userInfo)
    if(res.errno === 0) {
      return await context.dispatch('login', userInfo);
    } else {
      return false;
    }
  },
  
  
  logout(context) {
    context.commit('logout'); //修改登录状态
  },
  
  
}

export default new Vuex.Store({
  state,
  actions,
  mutations,
  //getters,
  modules: {
    token,
    user
  },
  strict: debug,
  plugin: debug ? [createLogger()] : [] //调试模式加入日志插件
})
